package com.xysq.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.xysq.lemon.R;
import com.xysq.util.AlipayOrderInfoBuilder;
import com.xysq.util.Base64;
import com.xysq.util.Keys;
import com.xysq.util.PropertiesUtil;
import com.xysq.util.Result;
import com.xysq.util.UseUtil;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;

import butterknife.InjectView;

/**
 * @Author huangdongkai
 * 充值
 */

public class RechargeActivity extends BaseActivity implements View.OnClickListener {

    @InjectView(R.id.edit_money)
    EditText moneyEdit;
    @InjectView(R.id.btn_rechange)
    Button rechangeBtn;

    private String loginName;
    private static final int MESSAGE_ALIPAY = 0;
    private static final String ALGORITHM = "RSA";
    private static final String SIGN_ALGORITHMS = "SHA1WithRSA";
    private static final String DEFAULT_CHARSET = "UTF-8";
    private String mPayInfo;
    private String mMoneyCount;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recharge);
        initView();
    }

    private void initView() {
        rechangeBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        if (view == rechangeBtn) {
            mMoneyCount = moneyEdit.getText().toString();
            toAliPay();
        }
    }

    private void toAliPay() {
        String orderInfo = createAlipayInfo();
        //Log.d(TAG, "orderInfo:" + orderInfo);
        String sign = sign(orderInfo);
        try {
            // 仅需对sign 做URL编码
            sign = URLEncoder.encode(sign, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        mPayInfo = orderInfo + "&sign=\"" + sign + "\"&"
                + getSignType();
        new Thread(new AlipayRunnable()).start();
    }

    private String createAlipayInfo() {
        AlipayOrderInfoBuilder builder = new AlipayOrderInfoBuilder();
        String tradeNo = Math.round(Math.random() * 89 + 10) + UseUtil.getCurrentDate()
                + loginName;
        //Log.d(TAG, "tradeNo:" + tradeNo);
        builder.setOutTradeNo(tradeNo);
        builder.setSubject("钱包充值");
        builder.setBody(getOrderBody());
        builder.setTotalFee(mMoneyCount);
        String url = PropertiesUtil.getAlipayNotifyRechargeUrl();
        builder.setNotifyUrl(url);
        return builder.build();
    }

    private String sign(String orderInfo) {
        try {
            PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(Keys.PRIVATE));
            KeyFactory keyf = KeyFactory.getInstance(ALGORITHM);
            PrivateKey priKey = keyf.generatePrivate(priPKCS8);
            java.security.Signature signature = java.security.Signature
                    .getInstance(SIGN_ALGORITHMS);
            signature.initSign(priKey);
            signature.update(orderInfo.getBytes(DEFAULT_CHARSET));
            byte[] signed = signature.sign();
            return Base64.encode(signed);
        } catch (NoSuchAlgorithmException | InvalidKeySpecException | InvalidKeyException | UnsupportedEncodingException | SignatureException e) {
            e.printStackTrace();
        }
        return null;
    }

    private class AlipayRunnable implements Runnable {

        @Override
        public void run() {
            // 构造PayTask 对象
            PayTask alipay = new PayTask(RechargeActivity.this);
            // 调用支付接口
            String result = alipay.pay(mPayInfo);

            Message msg = new Message();
            msg.what = MESSAGE_ALIPAY;
            msg.obj = result;
            mAlipayHandler.sendMessage(msg);
        }
    }

    private String getOrderBody() {
        return String.format("券控钱包充值:%s元", mMoneyCount);
    }

    Handler mAlipayHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Result result = new Result((String) msg.obj);
            switch (msg.what) {
                case MESSAGE_ALIPAY:
                    String resultStatus = result.resultStatus;

                    // 判断resultStatus 为"9000"则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        Toast.makeText(RechargeActivity.this, "充值成功",
                                Toast.LENGTH_SHORT).show();
                        setResult(RESULT_OK);
                        finish();
                    } else {
                        // 判断resultStatus 为非"9000"则代表可能支付失败
                        // "8000" 代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            Toast.makeText(RechargeActivity.this, "充值结果确认中",
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(RechargeActivity.this, "充值失败",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    };

    public String getSignType() {
        return "sign_type=\"RSA\"";
    }
}
